#include "stdafx.h"
#include "TinyCapture.h"
#include "GraphicArea.h"
#include "GLHandler.h"
#include "Utility.h"
using namespace Utility;
extern GLfloat zoomDelta;

// GraphicArea
IMPLEMENT_DYNAMIC(GraphicArea, CStatic)

GraphicArea::GraphicArea(ComPortHandler& comHandler):curComHandler(comHandler)
{
	m_pProgressDlg=NULL;
	GLHandler::setComPortHandler(&comHandler);
}

GraphicArea::~GraphicArea()
{
}

BEGIN_MESSAGE_MAP(GraphicArea, CStatic)
	ON_WM_ERASEBKGND()
	ON_WM_PAINT()
	ON_WM_CREATE()
	ON_WM_SIZE()
	ON_WM_MOUSEWHEEL()
	ON_WM_TIMER()
	ON_WM_RBUTTONDOWN()
	ON_COMMAND(ID_POPMENU_LOADMODEL, &GraphicArea::OnPopmenuLoadmodel)
	ON_COMMAND(ID_POPMENU_DEFAULTMODEL, &GraphicArea::OnPopmenuDefaultmodel)
END_MESSAGE_MAP()

BOOL GraphicArea::OnEraseBkgnd(CDC* pDC)
{
	return TRUE;
}

void GraphicArea::OnPaint()
{
	CPaintDC dc(this); // device context for painting
	GLHandler::renderScene();
	SwapBuffers(m_pDC->GetSafeHdc());
}

int GraphicArea::OnCreate(LPCREATESTRUCT lpCreateStruct)
{
	if (CStatic::OnCreate(lpCreateStruct) == -1)
		return -1;
	return 0;
}

void GraphicArea::OnSize(UINT nType, int cx, int cy)
{
	GLHandler::setViewPort((GLsizei)cx,(GLsizei)cy);
	CStatic::OnSize(nType, cx, cy);
}

BOOL GraphicArea::OnMouseWheel(UINT nFlags, short zDelta, CPoint pt)
{
	int delta=(int)zDelta;
	zoomDelta+=delta/WHEEL_DELTA*0.1;
	return CStatic::OnMouseWheel(nFlags, zDelta, pt);
}

void GraphicArea::OnTimer(UINT_PTR nIDEvent)
{
	GLHandler::getRotateFromComHandler();
	Invalidate(FALSE);
	CStatic::OnTimer(nIDEvent);
}

void GraphicArea::OnRButtonDown(UINT nFlags, CPoint point)
{
	CMenu menu, *pSubMen;
	menu.LoadMenu(IDR_MENU_LOADOBJ);
	pSubMen = menu.GetSubMenu(0);
	ClientToScreen(&point);
	pSubMen->TrackPopupMenu(TPM_LEFTALIGN, point.x, point.y, this);
	CStatic::OnRButtonDown(nFlags, point);
}

void GraphicArea::OnPopmenuLoadmodel()
{
	if (m_pProgressDlg!=NULL)
		return;

	m_pProgressDlg = new ProgressDialog();
	m_pProgressDlg->Create(IDD_PROGRESS_DIALOG, this);

	TCHAR szFilters[]= _T("obj file (*.obj)|*.obj|All Files (*.*)|*.*||");
	CFileDialog fileDlg(TRUE, _T("obj"), _T("*.obj"),OFN_FILEMUSTEXIST | OFN_HIDEREADONLY, szFilters);
	if(fileDlg.DoModal() == IDOK)
	{
		CString file = fileDlg.GetPathName();
		file.Replace('\\','\/');
		USES_CONVERSION;
		char* fileFullName = W2A(file.GetBuffer(file.GetLength() + 1));
		m_pProgressDlg->CenterWindow(this);
		m_pProgressDlg->ShowWindow(SW_SHOW);
		m_pProgressDlg->UpdateWindow();
		if (!GLHandler::generateGLMCallList(fileFullName, 2.0))
		{
			Helper::errInfoDialog(L"Open Obj File Failed!");
		}
		this->Invalidate(FALSE);
	}
	m_pProgressDlg->DestroyWindow();
	delete m_pProgressDlg;
	m_pProgressDlg = NULL;
}

void GraphicArea::OnPopmenuDefaultmodel()
{
	GLHandler::isShowCusModel = false;
}




